//
//  MyDocument.m
//  MapEdit
//
//  Created by Steven Canfield on 7/06/07.
//  Copyright __MyCompanyName__ 2007 . All rights reserved.
//

#import "SCMDocument.h"

#define int8 char
#define int16 short
#define int32 int

@implementation SCMDocument

- (id)init
{
    self = [super init];
    if (self) {
    
        // Add your subclass-specific initialization here.
        // If an error occurs here, send a [self release] message and return nil.
    
    }
    return self;
}

- (NSString *)windowNibName
{
    return @"MyDocument";
}

- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
    [super windowControllerDidLoadNib:aController];
	/* Load Map Data */
	NSData * dimensionData = [_chkFile dataForChunkNamed:@"DIM "];
	[dimensionData getBytes:&_dimensions range:NSMakeRange( 0, sizeof( chk_dim_t ))];
	swap_chk_dim( &_dimensions );
	
	chk_era_t era;
	NSData * tilesetData = [_chkFile dataForChunkNamed:@"ERA "];
	[tilesetData getBytes:&era length:sizeof( chk_era_t )];
	swap_chk_era( &era );

	NSArray * tilesetNames = [NSArray arrayWithObjects:@"badlands", @"platform", @"install", @"ashworld", @"jungle", @"desert", @"ice", @"twilight", NULL];
	NSLog(@"%i = era.tileset ", era.tileset );
	_tilesetName = [tilesetNames objectAtIndex:era.tileset];
	[self loadTilesetData:_tilesetName];
	
	/* Header */
	[self loadFileHeader];

	_stringManager = [[StringManager alloc] initWithData:[_chkFile dataForChunkNamed:@"STR "]];
		
	/* Terrain */
	_map = [[TileMap alloc] initWithData:[_chkFile dataForChunkNamed:@"MTXM"] size:NSMakeSize( _dimensions.width, _dimensions.height )];
	
	/* Unit + Doodad */
	_unitList = [[UnitList alloc] initWithData:[_chkFile dataForChunkNamed:@"UNIT"]];
	[_chkFile setSaveCallbackForChunkNamed:@"UNIT" target:_unitList selector:@selector(serializedUnitList)];
	
	
	/* Player Settings */
	[_playerSettingController loadIOWN:[_chkFile dataForChunkNamed:@"IOWN"]];
	[_playerSettingController loadOWNR:[_chkFile dataForChunkNamed:@"OWNR"]];
	[_playerSettingController loadSIDE:[_chkFile dataForChunkNamed:@"SIDE"]];
	[_playerSettingController loadFORC:[_chkFile dataForChunkNamed:@"FORC"]];
	[_playerSettingController loadCOLR:[_chkFile dataForChunkNamed:@"COLR"]];
	[_playerSettingController setStringManager:_stringManager];
	
	[_chkFile setSaveCallbackForChunkNamed:@"IOWN" target:_playerSettingController selector:@selector(serializedIOWN)];
	[_chkFile setSaveCallbackForChunkNamed:@"OWNR" target:_playerSettingController selector:@selector(serializedOWNR)];
	[_chkFile setSaveCallbackForChunkNamed:@"SIDE" target:_playerSettingController selector:@selector(serializedSIDE)];
	[_chkFile setSaveCallbackForChunkNamed:@"FORC" target:_playerSettingController selector:@selector(serializedFORC)];
	[_chkFile setSaveCallbackForChunkNamed:@"COLR" target:_playerSettingController selector:@selector(serializedCOLR)];
	
	[_playerSettingController reloadAllData];
	
	/* Scenario */
	_locationList = [[LocationList alloc] initWithData:[_chkFile dataForChunkNamed:@"MRGN"]];
	[_locationList setStringManager:_stringManager];
	
	_triggerManager = [[TriggerManager alloc] initWithData:[_chkFile dataForChunkNamed:@"TRIG"]];
	
	NSLog( [DATManager starcraftFilesDirectory] );
		
	[miniMapView setTileMap:_map];
	[miniMapView setTileList:_tileList];
	[miniMapView setTileGroupList:_groupList];
	[miniMapView setPalette:_palette];
	[miniMapView setUnitList:_unitList];
	[miniMapView setNeedsDisplay:YES];

	/*
	 [view setTileMap:_map];
	[view setPalette:_palette];	
	[view setTileGroupList:_groupList];
	[view setTileList:_tileList];
	[view setTilePieceList:_pieceList];
	[view setUnitList:_unitList];
	[view setLocationList:_locationList];
	[view setNeedsDisplay:YES];
	//NSLog(@"%@", NSStringFromClass( [fastView class] ));
	*/
	[fastView setTileMap:_map];
	[fastView setPalette:_palette];	
	[fastView setTileGroupList:_groupList];
	[fastView setTileList:_tileList];
	[fastView setTilePieceList:_pieceList];
	[fastView setNeedsDisplay:YES];

	[[scrollView horizontalScroller] setTarget:fastView];
	[[scrollView verticalScroller] setTarget:fastView];
	[fastView setHorizontalScroller:[scrollView horizontalScroller]];
	[fastView setVerticalScroller:[scrollView verticalScroller]];
	
	[fastView setNeedsDisplay:YES];

	[_playerSettingController reloadAllData];
}

- (void)loadTilesetData:(NSString *)tilesetName {
	NSArray * broodTilesets = [NSArray arrayWithObjects:@"ice", @"desert", @"twilight", NULL];
	
	MPQArchive * dataArchive;
	if( [broodTilesets containsObject: tilesetName ] ) {
		dataArchive = [MPQArchive archiveWithPath:[NSString stringWithFormat:@"%@/Brood War Data", [DATManager starcraftFilesDirectory]]];
	} else {
		dataArchive = [MPQArchive archiveWithPath:[NSString stringWithFormat:@"%@/StarCraft Data", [DATManager starcraftFilesDirectory]]];
	}
	NSError * err;
	
	NSString * tilesetPath = [NSString stringWithFormat:@"tileset\\%@", tilesetName];	
	NSLog( tilesetPath );
	
	NSData * paletteData = [dataArchive copyDataForFile:[NSString stringWithFormat:@"%@.wpe", tilesetPath] error:&err];
	_palette = [[ColorPalette alloc] initWithData:paletteData];
	
	NSData * tilePieceData = [dataArchive copyDataForFile:[NSString stringWithFormat:@"%@.vr4", tilesetPath] error:&err];
	_pieceList = [[TilePieceList alloc] initWithData:tilePieceData palette:_palette];

	NSData * tileData = [dataArchive copyDataForFile:[NSString stringWithFormat:@"%@.vx4", tilesetPath] error:&err];
	_tileList = [[TileList alloc] initWithData:tileData pieceList:_pieceList palette:_palette];
	
	NSData * tileGroupData = [dataArchive copyDataForFile:[NSString stringWithFormat:@"%@.cv5", tilesetPath] error:&err];
	_groupList = [[TileGroupList alloc] initWithData:tileGroupData];
}

- (void)loadFileHeader {
	_fileInfoManager = [[FileInfoManager alloc] init];
	NSData * fileInfoData = [_chkFile dataForChunkNamed:@"TYPE"];
	chk_type_t type;
	[fileInfoData getBytes:&type length:[fileInfoData length]];
	
	fileInfoData = [_chkFile dataForChunkNamed:@"VER "];
	chk_ver_t ver;
	[fileInfoData getBytes:&ver length:[fileInfoData length]];

	fileInfoData = [_chkFile dataForChunkNamed:@"IVER"];
	chk_iver_t iver;
	[fileInfoData getBytes:&iver length:[fileInfoData length]];

	fileInfoData = [_chkFile dataForChunkNamed:@"IVE2"];
	chk_ive2_t ive2;
	[fileInfoData getBytes:&ive2 length:[fileInfoData length]];

	fileInfoData = [_chkFile dataForChunkNamed:@"VCOD"];
	chk_vcod_t vcod;
	[fileInfoData getBytes:&vcod length:[fileInfoData length]];
	
	[_fileInfoManager setType:type];
	[_chkFile setSaveCallbackForChunkNamed:@"TYPE" target:_fileInfoManager selector:@selector(serializedType)];
	[_fileInfoManager setVersion1:ver];
	[_chkFile setSaveCallbackForChunkNamed:@"VER " target:_fileInfoManager selector:@selector(serializedVersion1)];
	[_fileInfoManager setVersion2:iver];
	[_chkFile setSaveCallbackForChunkNamed:@"IVER" target:_fileInfoManager selector:@selector(serializedVersion2)];
	[_fileInfoManager setVersion3:ive2];
	[_chkFile setSaveCallbackForChunkNamed:@"IVE2" target:_fileInfoManager selector:@selector(serializedVersion3)];
	[_fileInfoManager setVerificationCode:vcod];
	[_chkFile setSaveCallbackForChunkNamed:@"VCOD" target:_fileInfoManager selector:@selector(serializedVerificationCode)];
}

- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)outError;
{
	[_archive addFileWithData:[_chkFile serialize]  filename:@"staredit\\scenario.chk" parameters:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:MPQOverwrite] error:outError];
	NSString * path = [NSString stringWithFormat:@"%@", [absoluteURL path]];
	[_archive writeToFile:path atomically:YES error:outError];
	if( *outError != NULL ) {
		NSLog(@"Error is %@", [*outError description] );
		return NO;
	}
	return YES;
}

- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError
{
	NSError * err = NULL;
	_archive = [MPQArchive archiveWithPath:[absoluteURL path] error:&err];
	[_archive retain];
	
	if( _archive != NULL && err == NULL ) {
		MPQFile * entry = [_archive openFile:@"staredit\\scenario.chk" error:&err];
		NSData * data = [entry copyDataToEndOfFile];
		_chkFile = [[CHKFile alloc] initWithData:[data copy]];
		return YES;
	} else {
		NSLog( [err description] );
	}
	
	*outError = err;
	return NO;
	
}

- (NSSize)windowWillResize:(NSWindow *)sender toSize:(NSSize)proposedFrameSize {
	//NSLog( NSStringFromSelector( _cmd ));
	if( proposedFrameSize.width > [view frame].size.width + [NSScroller scrollerWidth] + 2) {
		proposedFrameSize.width = [view frame].size.width +  [NSScroller scrollerWidth] + 2 ;
	}
	if( proposedFrameSize.height > [view frame].size.height +  [NSScroller scrollerWidth] + 59 ) {
		proposedFrameSize.height = [view frame].size.height +  [NSScroller scrollerWidth] + 59;
	}
	return proposedFrameSize;
}

@end
